package com.jzqf.bluetooth.client

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.ParcelUuid
import android.util.Log
import com.jzqf.bluetooth.Api
import com.jzqf.bluetooth.FormatUtil

object BleUtil {
    private val TAG = "【BleUtil】"
    private var bluetoothAdapter: BluetoothAdapter? = null

    fun initBleBluetooth(context: Context) {
        val bluetoothManager =
            context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothAdapter = bluetoothManager.adapter
        if (bluetoothAdapter == null || bluetoothAdapter?.isEnabled == false) {
            val intentBlue = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
//            context.startActivityForResult(intentBlue, REQUEST_CODE_BLUE)
            bluetoothAdapter?.enable()
            Log.d(TAG, "设备未开启蓝牙")
            return
        }
        if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Log.d(TAG, "设备不支持BLE低功耗")
            return
        }
    }

    fun startScan() {
        val bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner
        bluetoothLeScanner?.startScan(scanFilter(), createScanSetting(), object : ScanCallback() {
            override fun onBatchScanResults(results: MutableList<ScanResult>?) {
                super.onBatchScanResults(results)
//                Log.d(TAG, "接收回调时间--")
                if (results.isNullOrEmpty()) {
                    Log.d(TAG, "results is  null 的")
                    return
                }
                results.forEach {
                    if (it.device != null) {
                        val d = Math.pow(10.0, (Math.abs(it.rssi) - 70) / (10 * 2.0))
                        val juli: String = java.util.Formatter().format("%.2f", d).toString()
                        var uuidStr = ""
                        it.device.uuids?.forEach { uuid ->
                            uuidStr += "\n uuid=$uuid"
                        }
                        it.scanRecord?.serviceUuids?.forEach { uuid ->
                            uuidStr += "\n serviceUuid=$uuid"
                        }

                        if (uuidStr.isNotEmpty()) {
                            Log.d(
                                TAG,
                                "onBatchScanResults:${it.device.name},MAC=${it.device.address}" +
                                        "\n rssi=${it.rssi}" +
                                        "\n 距离=$juli m" +
                                        "\n $uuidStr"
                            )
                        }
                    } else {
                        Log.d(TAG, "device 为空")
                    }
                }
            }

            override fun onScanFailed(errorCode: Int) {
                super.onScanFailed(errorCode)
                Log.d(TAG, "onScanFailed:${errorCode}")
            }

            override fun onScanResult(callbackType: Int, result: ScanResult?) {
                super.onScanResult(callbackType, result)
                Log.d(TAG, "onScanResult:${result?.device?.name},MAC=${result?.device?.address}")
            }
        })
    }

    private fun createScanSetting(): ScanSettings? {
        val builder = ScanSettings.Builder()
        //SCAN_MODE_LOW_POWER--------耗电最少，扫描时间间隔最短
        //SCAN_MODE_BALANCED---------平衡模式，耗电适中，扫描时间间隔一般，我使用这种模式来更新设备状态
        //SCAN_MODE_LOW_LATENCY---------最耗电，扫描延迟时间短，打开扫描需要立马返回结果可以使用
        builder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
        builder.setReportDelay(400);//设置延迟返回时间
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            builder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
        }
        return builder.build()
    }

    private fun scanFilter(): List<ScanFilter> {
        val list = mutableListOf<ScanFilter>()
        val scanFilter =
            ScanFilter.Builder().setServiceUuid(ParcelUuid(Api.UUID_SERVICE)).build()
        list.add(scanFilter)
        return list
    }

    fun startScanLe() {
        bluetoothAdapter?.startLeScan { device, rssi, scanRecord ->
            if (device?.name != null) {
                Log.d(
                    TAG, "device=${device.name} address=${device.address}  rssi=${rssi} \n"
                            + "data=${FormatUtil.bytes2HexString(scanRecord)}"
                )
            }
        }
    }

    /**
     *
     * 02011a0a0947616c617879205338020af9020af91107776a6d20808ae691a7e79daae7829ce8000000000000000000000000000000000000000000000000
     * 02 数据长度
     * 01 普通发现模式
     * 1a
     * 0a
     */
    private fun parseData(byteArray: ByteArray){

    }
}